"use strict";

const BaseModel = require("../basics/mysql/mapper");
const Result = require("../basics/result");
class HomeModel extends BaseModel {
  constructor(cloud) {
    super(cloud, "user");
  }

  /**
   * 获取实例
   * @param {*} cloud 
   */
  static getInstant(cloud) {
    return new HomeModel(cloud);
  }


  /**
   * 用户登录
   * @param {*} openId 
   * @param {*} mixNick 
   * @param {*} boardtime 
   */
  async login(openId, mixNick, boardtime) {
    const ex = this.createExample();
    ex.criteria.andEqual("openId", openId);
    let data = await this.selectOneByExample(ex);
    if (!data) {
      try {
        data.id = await this.insertOne({ openId, mixNick, nickname: "", fraction: 0, boardtime, isfirst: 1 });
      } catch (error) {
        data = await this.selectOneByExample(ex);
      }
    }
    return data;
  }


  /**
   * 查询当条
   * @param {*} openId 
   */
  async selectOneByOpenId(openId) {
    const ex = this.createExample();
    ex.criteria.andEqual("openId", openId);
    const data = await this.selectOneByExample(ex);
    if (!data) {
      throw Result.error(Result.constant.loginfail, "请先登录");
    }
    return data;
  }

}

module.exports = HomeModel;